package com.howard.servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.howard.entity.User;
import com.howard.exception.ServiceException;
import com.howard.service.UserService;

/**
 * 测试servlet 用
 *
 * @author <a href="mailto:howard.he0329@gmail.com">Howard.He</a>
 *
 */
@WebServlet(urlPatterns = "/hello.do", name = "HelloServlet")
@SuppressWarnings("serial")
public class HelloServlet extends HttpServlet {

    private static Logger logger = LoggerFactory
            .getLogger(HelloServlet.class);

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
    	WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(req.getServletContext());
    	UserService userService = ctx.getBean(UserService.class);
    	try {
			User user = userService.searchUserById(2);
			logger.debug("user count: " + user.getMail());
		} catch (ServiceException e) {
			e.printStackTrace();
		}
		req.setAttribute("maxMemory", Runtime.getRuntime().maxMemory()/1000/1024 + "MB");
		req.setAttribute("freeMemory", Runtime.getRuntime().freeMemory()/1000/1024 + "MB");
		req.setAttribute("totalMemory", Runtime.getRuntime().totalMemory()/1000/1024 + "MB");
		req.setAttribute("available", Runtime.getRuntime().availableProcessors());
        RequestDispatcher res = req.getRequestDispatcher("jsp/hello.jsp");
        res.forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doGet(req, resp);
    }
}
